package com.thprojects.myphotomemories.view;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;

import com.thprojects.myphotomemories.R;
import com.thprojects.myphotomemories.controller.DbController;
import com.thprojects.myphotomemories.controller.GuiController;
import com.thprojects.myphotomemories.controller.WebController;
import com.thprojects.myphotomemories.model.LoggedUser;

public class LoginView extends Activity {

	EditText mName, mPassword;
	Button mOk, mCancel, mRegister;
	DbController mDbController;
	ProgressDialog mProgressDialog;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_view);
		
		mDbController = DbController.getDbController(this);
		
		mName = (EditText)findViewById(R.id.login_name);
		mPassword = (EditText)findViewById(R.id.login_password);

		mOk = (Button)findViewById(R.id.login_ok);
		mCancel = (Button)findViewById(R.id.login_cancel);
		mRegister = (Button)findViewById(R.id.login_register_btn);
		
		
		mName.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				//TODO
			}
		});
		
		
		mCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
				GuiController.showMain(LoginView.this);
			}
		});
	    
		mOk.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				LoginUserTask lut = new LoginUserTask();
				lut.execute();
			}
		});
	    
	    mRegister.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				GuiController.showRegister(LoginView.this);
				finish();
			}
		});
		
	}
	
	private void loginUser(){
		String name = ((EditText)findViewById(R.id.login_name)).getText().toString();
		String pwd = ((EditText)findViewById(R.id.login_password)).getText().toString();
		

		if (WebController.checkCorrectCredentials(this, name, pwd)){
			LoggedUser.login(name, pwd);
		}
		else{
			GuiController.showError(this, "Could not login. please check the credentials you provided");
		}
		
	}
	
	private class LoginUserTask extends AsyncTask<Void, Void, Void>{	
		@Override
		protected Void doInBackground(Void... v) {			
			loginUser();
			return null;
		}

		@Override
		protected void onPostExecute(Void v) {
			super.onPostExecute(v);
			mProgressDialog.cancel();
			finish();
			GuiController.showWebPhotos(LoginView.this);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog = ProgressDialog.show(LoginView.this, "Logging in", "Please wait...");
		}
	}
	
}

